package com.easy.dev.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ClassUtils {

    private static Map<Class, Field[]> cacheFields = new HashMap<>();
    private static Map<Class, Map<String, Field>> cacheField = new HashMap<>();

    /**
     * 根据类获取类属性反射field数组
     * @param clazz
     * @return
     */
    public static Field[] getFields(Class clazz) {
        Field[] fields = cacheFields.get(clazz);
        if (fields == null) {
            fields = clazz.getDeclaredFields();
            setFieldsAccessibleFalse(fields);
            cacheFields.put(clazz, fields);
        }
        return fields;
    }

    /**
     * 根据类和属性名称获取Field
     * @param clazz
     * @param name
     * @return
     */
    public static Field getFieldByClassAndName(Class clazz, String name) {
        Map<String, Field> cache = cacheField.get(clazz);
        if (cache == null) {
            Field[] fields = getFields(clazz);
            cache = new HashMap<>();
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                cache.put(field.getName(), field);
            }
            cacheField.put(clazz, cache);
        }
        return cache.get(name);
    }

    public static void setFieldsAccessibleFalse(Field...fields) {
        for (int i = 0; i < fields.length; i++) {
            fields[i].setAccessible(false);
        }
    }


}
